<?php


namespace app\admin\controller\auth;


use app\admin\service\RequestService;
use app\model\AdminLog;
use app\model\auth\Admin;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class AdminLogController extends AController {

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function index(RequestService $curdService): \think\response\Json
    {
        $query = new AdminLog();
        $list = $curdService->read($query);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }


    /**
     * 修改密码
     * @param Request $request
     * @return \think\response\Json
     */
    private function setPassword($data): \think\response\Json
    {
        try {
            validate(AdminValidate::class)
                ->scene('password')
                ->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonError($e->getError());
        }

        Admin::update([
            'password' => $data['password']
        ], [
            'id' => $data['id']
        ]);

        return jsonSuccess();

    }


    public function export(){// 不限制脚本执行时间以确保导出完成


        $date = request()->param('date','');

        if (!$date){
            return jsonError('请选择日期');
        }

        $header = [
            'ac.name' => '栏目',
            'a.title' => '标题',
            'a.content' => '内容',
            'a.hits' => '点击',
            'a.create_time' => '添加时间',
            'a.update_time' => '更新时间',
        ];

        $data = $this->model->alias('a')
            ->field(array_keys($header))
            ->order('create_time desc')
            ->join('article_cate ac', 'a.cate_id = ac.id')
            ->whereTime('a.create_time', 'between', $date)
            ->select()->toArray();

        //浏览器访问渲染下载
        $csv = new Thinkcsv(rand(100000000,9999999999).'.csv', array_values($header), $data);
        $csv->export();

    }


    protected function formatList($list){
        $list = $list->each(function ($v) {
            $v->groupTitle = getRelValue($v->groups[0], 'title');
        });
        return $list;
    }


}
